import os
import webbrowser
from datetime import datetime, timedelta

import pandas as pd

import settings


def change_dict_keys(data_dict):
    """
    将dict的key替换为 dataframe 中的 index（时间换股票名称）
    :param data_dict: dict{data_string: DataFrame}
    :return: dict
    """
    new_dict = {}
    for key, value in data_dict.items():
        # 提取所有股票名称
        for index, row in value.iterrows():
            if index not in new_dict.keys():
                row['date'] = key
                new_df = pd.DataFrame(columns=row.index.values)
                new_df = new_df.append(row, ignore_index=True)
                new_df.set_index('date', inplace=True)
                new_dict[index] = new_df
            else:
                new_dict[index].loc[key] = row

    return new_dict


def select_data_between(start_date_string, end_date_string, data_dict):
    """
    在 key 为时间的 dict 数据中选取指定时间段的数据
    :return: dict
    """
    new_data = {}
    date = start_date_string
    date_time = datetime.strptime(date, '%Y-%m-%d')
    end_date_time = datetime.strptime(end_date_string, '%Y-%m-%d')
    keys = data_dict.keys()
    while date_time <= end_date_time:
        if date in keys:
            new_data[date] = data_dict[date]
        date_time = date_time + timedelta(days=1)
        date = date_time.strftime("%Y-%m-%d")
    return new_data


def show_charts(filename):
    """
    在浏览器中显示 charts 目录下的文件
    :param filename:
    :return:
    """
    project_path = os.path.abspath('..').replace('\\', '/')
    file_path = 'file:///' + project_path + '/charts/' + filename
    webbrowser.open_new_tab(file_path)


def height_prct(percentage):
    return (settings.HEIGHT / 100) * percentage


def width_prct(percentage):
    return (settings.WIDTH / 100) * percentage
